<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/29
 * Time: 11:08
 */

namespace Home\Logic;


use Admin\Logic\MoneyLogLogic;
use Common\Utils\Constants;
use Home\Model\Page;
use Think\Exception;
use Think\Log;

class LotteryLogLogic
{
    /**
     * 分页条件查询
     * @param $map 查询条件
     * @param $pagenumber 页号
     * @param $pagesize 页面大小
     * @return mixed
     */
    public function getByConditionPage($map, $pagenumber, $pagesize)
    {
        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $list = D('LotteryLog')->where($map)->limit($limit)->order('id desc')
            ->select();
        foreach ($list as $key=>$value){
            $list[$key]['create_time'] = date('Y/m/d',$value['create_time']);
        }
        $data['list'] = $list;
        $count = D('LotteryLog')->where($map)->count();
        $page = new Page($pagenumber, $count, $pagesize);
        $page = (array)$page;//转换为数组
        $data['page'] = $page;
        return $data;
    }

    /**
     * 抽奖
     * @param $user_id int 用户id
     * @return array status 0失败 1成功 2系统错误 3金币不足 4
     */
    public function lottery($user_id){
        $gold = D('User')->where(array('id'=>$user_id))->getField('gold');
        $config = D('Config')->where(array('name'=>Constants::CONFIG_LOTTERY_GOLD))->find();
//                    $room = $model->table('t_room')->where(array('id'=>$log['room_id']))->find();
        $money = $config['value'];
        if(!is_numeric($money) || $money<0){
            return array('status'=>2);
        }
        if($gold < $money){
            return array('status'=>3);
        }
        $model = M();
        $model->startTrans();
        try {
            $prize_id = $this->doLottery();
            $prize = $model->table('t_prize')->where(array('id'=>$prize_id))->find();
            $this->decGold($gold,$prize,$money,$user_id,$model);
            $this->addLotteryLog($prize,$user_id,$money,$model);
            $model->commit();
            return array('status'=>1,'prize'=>$prize);
        }catch (Exception $e){
            Log::write('lottery---:'.$e->getMessage());
            $model->rollback();
            return array('status'=>0);
        }
    }

    /**
     * 添加抽奖记录
     * @param $prize array 奖品
     * @param $user_id
     * @param $money int 抽奖所需金币
     * @param $model object
     */
    private function addLotteryLog($prize,$user_id,$money,$model){

        if($prize['type'] != Constants::PRIZE_TYPE_OTHER){
            $log['status'] = 1;//已经发放
            if($prize['type'] == Constants::PRIZE_TYPE_INTEGRAL || $prize['type'] == Constants::PRIZE_TYPE_GOLD){
                //发放奖品
                $this->releasePrize($prize,$user_id,$model);
            }
        }else{
            $log['status'] = 0;//等待领取
        }
        $log['title'] = $prize['title'];
        $log['prize_id'] = $prize['id'];
        $log['money'] = $money;
        $log['type'] = $prize['type'];
        $log['user_id'] = $user_id;
        $log['create_time'] = time();
        $model->table('t_lottery_log')->add($log);
    }

    //发放奖品
    private function releasePrize($prize,$user_id,$model){
        $money = $prize['number'];
        if($prize['type'] == Constants::PRIZE_TYPE_INTEGRAL){
            $model->table('t_user')->where(array('id' => $user_id))->setInc('integral', $money);
            $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('integral');
            $money_type = Constants::MONEY_TYPE_INTEGRAL;
        }else{
            $model->table('t_user')->where(array('id' => $user_id))->setInc('gold', $money);
            $money_type = Constants::MONEY_TYPE_GOLD;
            $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
        }
        $remark = '抽奖获得(' . $prize['title'] . ')';
        $moneyLogic = new MoneyLogLogic();
        $moneyLogic->saveMoneyLog($money,
            $currentMoney,
            Constants::MONEY_SOURCE_LOTTERY,
            Constants::PUT_TYPE_IN,
            $remark, $user_id, $money_type, $model);
    }

    /**
     * 扣除用户金币
     * @param $gold int 用户当前金币
     * @param $prize array 奖品
     * @param $money int 所需金额
     * @param $user_id int 用户id
     * @param $model object
     */
    private function decGold($gold,$prize,$money,$user_id,$model){
        $remark = '使用金币抽奖(' . $prize['title'] . ')';
        $moneyLogic = new MoneyLogLogic();
        $model->table('t_user')->where(array('id' => $user_id))->setDec('gold', $money);
        $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
        $moneyLogic->saveMoneyLog($money,
            $currentMoney,
            Constants::MONEY_SOURCE_LOTTERY,
            Constants::PUT_TYPE_OUT,
            $remark, $user_id, Constants::MONEY_TYPE_GOLD, $model);
    }

    //执行抽奖 获取中奖奖品id
    private function doLottery(){
        $map['is_show'] = 1;
        $mop['is_delete'] = 0;
        $list = D('Prize')->where($map)->select();
        $prizeArray = array();
        foreach ($list as $key=>$value){
            $prizeArray[$value['id']]=$value['probability'];
        }
        return $this->get_rand($prizeArray);
    }

    private function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
}